package com.codemes.happylist.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;

/**
 * @author nscoffee
 */
public class CacheUtil {

    private static final String SECURE_KEY = "ALJDFLAKSUIOCVJLK234908&^&^%120398012&^$$#SDF4537234DF";

    public static String get(String key){
        String path = FilePathConst.RESOURCES_DIR_CACHE +File.separator+ DigestUtil.md5Hex(key);
        if(!FileUtil.exist(path)){
            return null;
        }
        String value = FileUtil.readString(new File(path),"utf-8");
        try {
            value = SecureUtil.des(SECURE_KEY.getBytes("utf-8")).decryptStr(value);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return value;
    }

    public static boolean delete(String key){
        String path = FilePathConst.RESOURCES_DIR_CACHE +File.separator+ DigestUtil.md5Hex(key);
        if(!FileUtil.exist(path)){
            return Boolean.TRUE;
        }
        return FileUtil.del(path);
    }

    public static File set(String key,String value){
        String path = FilePathConst.RESOURCES_DIR_CACHE +File.separator+ DigestUtil.md5Hex(key);
        try {
            value = SecureUtil.des(SECURE_KEY.getBytes("utf-8")).encryptHex(value);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return FileUtil.writeString(value,path,"utf-8");
    }
}
